package com.lanou3g.zjl.chating.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TabHost;
import android.widget.Toast;

import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.util.NetUtils;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.home.friends.FriendsFragment;
import com.lanou3g.zjl.chating.home.message.MessageFragment;
import com.lanou3g.zjl.chating.home.setting.SettingFragment;
import com.lanou3g.zjl.chating.base.BaseActivity;
import com.nineoldandroids.view.ViewHelper;

import butterknife.Bind;

/**
 * Created by dllo on 15/11/17.
 */
public class HomeActivity extends BaseActivity {
//    private static final String TAG = "HomeActivity";
    private NewMessageBroadcastReceiver msgReceiver;

    @Bind(R.id.mDrawerLayout)
    DrawerLayout mDrawerLayout;
    @Bind(android.R.id.tabhost)
    TabHost tabhost;
    private FragmentManager fm;

    @Override
    protected int getLayout() {
        return R.layout.activity_home;
    }

    /**
     * 初始化组件  加载tab页面
     */
    private void initView() {
        tabhost.setup();

        TabHost.TabSpec specMessage = tabhost.newTabSpec("message");
        View tabMessage = getLayoutInflater().inflate(R.layout.tab_message_indicator, null);
        specMessage.setIndicator(tabMessage);
        specMessage.setContent(R.id.messageFrm);
        tabhost.addTab(specMessage);

        TabHost.TabSpec specFriends = tabhost.newTabSpec("friends");
        View tabFriends = getLayoutInflater().inflate(R.layout.tab_friends_indicator, null);
        specFriends.setIndicator(tabFriends);
        specFriends.setContent(R.id.friendFrm);
        tabhost.addTab(specFriends);

        TabHost.TabSpec specSetting = tabhost.newTabSpec("setting");
        View tabSetting = getLayoutInflater().inflate(R.layout.tab_setting_indicator, null);
        specSetting.setIndicator(tabSetting);
        specSetting.setContent(R.id.settingFrm);
        tabhost.addTab(specSetting);
    }

    private void initFragment() {
        fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        ft.replace(R.id.messageFrm, new MessageFragment());
        ft.replace(R.id.friendFrm, new FriendsFragment());
        ft.replace(R.id.settingFrm, new SettingFragment());
        ft.commit();
    }

    @Override
    protected void initData() {

        //接收消息的广播
        newMessageReciver();
        //注册一个监听连接状态的listener
        connectionListener();
        initView();
        initFragment();
        initEvents();
    }

    /**
     * 注册接收新消息的广播
     */
    private void newMessageReciver() {

        //只有注册了广播才能接收到新消息，目前离线消息，在线消息都是走接收消息的广播（离线消息目前无法监听，在登录以后，接收消息广播会执行一次拿到所有的离线消息）
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);
    }

    //接收消息的广播
    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 注销广播
            abortBroadcast();

            // 消息id（每条消息都会生成唯一的一个id，目前是SDK生成）
            String msgId = intent.getStringExtra("msgid");
            //发送方
            String username = intent.getStringExtra("from");

            Log.i("lanou", username + ">>>>>>>>>>>>>>广播接收器响应<<<<<<<<<<<");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);

            Log.i("lanou", message.getBody() + ">>>>>>>>>>>>>>消息内容<<<<<<<<<<<");
            EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            // 如果是群聊消息，获取到group id
            if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                username = message.getTo();
            }
            if (!username.equals(username)) {
                // 消息不是发给当前会话，return
                return;
            }
        }
    }

    /**
     * //注册一个监听连接状态的listener
     */
    private void connectionListener() {
        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
    }

    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                        Toast.makeText(getApplicationContext(), "显示帐号已经被移除", Toast.LENGTH_SHORT).show();
                    } else if (error == EMError.CONNECTION_CONFLICT) {
                        // 显示帐号在其他设备登陆
                        Toast.makeText(getApplicationContext(), "帐号在其他设备登陆", Toast.LENGTH_SHORT).show();
                    } else {
                        if (NetUtils.hasNetwork(HomeActivity.this)) {
                            //连接不到聊天服务器
                            Toast.makeText(getApplicationContext(), "连接不到聊天服务器", Toast.LENGTH_SHORT).show();
                        } else {
                            //当前网络不可用，请检查网络设置
                            Toast.makeText(getApplicationContext(), "当前网络不可用，请检查网络设置", Toast.LENGTH_SHORT).show();
                        }

                    }
                }
            });
        }
    }

    /**
     * 打开左Fragment
     */
    public void OpenLeftMenu(View view) {
        mDrawerLayout.openDrawer(Gravity.LEFT);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED,
                Gravity.RIGHT);
    }

    /**
     * 控制抽屉
     */
    private void initEvents() {
        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {

            /**
             * 当抽屉滑动状态改变的时候被调用
             * 状态值是STATE_IDLE（闲置--0）, STATE_DRAGGING（拖拽的--1）, STATE_SETTLING（固定--2）中之一。
             * 抽屉打开的时候，点击抽屉，drawer的状态就会变成STATE_DRAGGING，然后变成STATE_IDLE
             */
            @Override
            public void onDrawerStateChanged(int newState) {

            }

            /**
             * 当抽屉被滑动的时候调用此方法
             * arg1 表示 滑动的幅度（0-1）
             */
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                View mContent = mDrawerLayout.getChildAt(0);
                View mMenu = drawerView;
                float scale = 1 - slideOffset;
                float rightScale = 0.8f + scale * 0.2f;

                if (drawerView.getTag().equals("LEFT")) {

                    float leftScale = 1 - 0.3f * scale;

                    ViewHelper.setScaleX(mMenu, leftScale);
                    ViewHelper.setScaleY(mMenu, leftScale);
                    ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));
                    ViewHelper.setTranslationX(mContent,
                            mMenu.getMeasuredWidth() * (1 - scale));
                    ViewHelper.setPivotX(mContent, 0);
                    ViewHelper.setPivotY(mContent,
                            mContent.getMeasuredHeight() / 2);
                    mContent.invalidate();
                    ViewHelper.setScaleX(mContent, rightScale);
                    ViewHelper.setScaleY(mContent, rightScale);
                } else {
                    ViewHelper.setTranslationX(mContent,
                            -mMenu.getMeasuredWidth() * slideOffset);
                    ViewHelper.setPivotX(mContent, mContent.getMeasuredWidth());
                    ViewHelper.setPivotY(mContent,
                            mContent.getMeasuredHeight() / 2);
                    mContent.invalidate();
                    ViewHelper.setScaleX(mContent, rightScale);
                    ViewHelper.setScaleY(mContent, rightScale);
                }
            }

            /**
             * 当一个抽屉被完全打开的时候被调用
             */
            @Override
            public void onDrawerOpened(View drawerView) {
            }

            /**
             * 当一个抽屉完全关闭的时候调用此方法
             */
            @Override
            public void onDrawerClosed(View drawerView) {
                mDrawerLayout.setDrawerLockMode(
                        DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(msgReceiver);
    }

    /**
     * 复写back键方法  让它不是直接退出而是在后台运行
     */
    @Override
    public void onBackPressed() {
//        super.onBackPressed();    注掉这句话的原因是因为 系统会默认调用back键的退出方法
        Intent i = new Intent(Intent.ACTION_MAIN);  // 选中主界面
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  // activity的model 保证只有一个activity（栈中只有一个）
        i.addCategory(Intent.CATEGORY_HOME);       // 设置该Activity随系统启动而运行(也就是开机状态不关闭？)
        startActivity(i);
    }

}

